package com.webex.ta.hydra.gui.autocomplete;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.basic.BasicComboPopup;
import java.awt.*;


/**
 * Created by IntelliJ IDEA.
 * User: vegaz
 * Date: 2010-8-16
 * Time: 14:32:29
 * To change this template use File | Settings | File Templates.
 */
public class AutoCompleteComboPopup extends BasicComboPopup {

    public AutoCompleteComboPopup(AutoCompleteComboBox combo) {
        super(combo);
    }

//    @Override
//    public void show() {
//        Point location = getPopupLocation();
//        show(comboBox, location.x, location.y);
//    }


    private Point getPopupLocation() {
        Dimension popupSize = comboBox.getSize();
        Insets insets = getInsets();

        // reduce the width of the scrollpane by the insets so that the popup
        // is the same width as the combo box.
        popupSize.setSize(popupSize.width - (insets.right + insets.left),
                getPopupHeightForRowCount(comboBox.getMaximumRowCount()));
        Rectangle popupBounds = computePopupBounds(0, comboBox.getBounds().height,
                popupSize.width, popupSize.height);
        Dimension scrollSize = popupBounds.getSize();
        Point popupLocation = popupBounds.getLocation();

        scroller.setMaximumSize(scrollSize);
        scroller.setPreferredSize(scrollSize);
        scroller.setMinimumSize(scrollSize);

        list.revalidate();

        return popupLocation;
    }

    protected int getPopupHeightForRowCount(int maxRowCount) {
        // Set the cached value of the minimum row count
        int minRowCount = Math.min(maxRowCount, list.getModel().getSize());
        int height = 0;
        ListCellRenderer renderer = list.getCellRenderer();
        Object value = null;

        for (int i = 0; i < minRowCount; ++i) {
            value = list.getModel().getElementAt(i);
            Component c = renderer.getListCellRendererComponent(list, value, i, false, false);
            height += c.getPreferredSize().height;
        }

        if (height == 0) {
            height = comboBox.getHeight();
        }

        Border border = scroller.getViewportBorder();
        if (border != null) {
            Insets insets = border.getBorderInsets(null);
            height += insets.top + insets.bottom;
        }

        border = scroller.getBorder();
        if (border != null) {
            Insets insets = border.getBorderInsets(null);
            height += insets.top + insets.bottom;
        }
        return height;
    }
}
